mui.init({
	statusBarBackground: '#f7f7f7'
});

mui.plusReady(function() {
	plus.screen.lockOrientation("portrait-primary");
	var settings = app.getSettings();
	var state = app.getState();
	var mainPage = mui.preload({
		"id": 'main',
		"url": 'main.html'
	});

	var toMain = function() {
		var ws;
		//使用定时器的原因：
		//可能执行太快，main页面loaded事件尚未触发就执行自定义事件，此时必然会失败
		var id = setInterval(function() {
			ws = plus.webview.getWebviewById('main');
			
			reloadMain()

			if(ws) {
				clearInterval(id);
				mui.fire(mainPage, 'gohome', null);
				mainPage.show("pop-in");
			}
		}, 200);
	};

	//检查登录状态
	if(settings.autoLogin && state.token) {
		toMain();
	} else {
		app.setState(null);
	}

	// close splash
	setTimeout(function() {
		//关闭 splash
		plus.navigator.closeSplashscreen();
	}, 600);
	//检查 "登录状态/锁屏状态" 结束
	var loginButton = document.getElementById('login');
	var accountBox = document.getElementById('account');
	var passwordBox = document.getElementById('password');
	var autoLoginButton = document.getElementById("autoLogin");
	var regButton = document.getElementById('reg');
	var forgetButton = document.getElementById('forgetPassword');

	// 登陆
	loginButton.addEventListener('tap', function(event) {
		var loginInfo = {
			account: accountBox.value,
			password: passwordBox.value
		};
		app.login(loginInfo, function(err) {
			if(err) {
				plus.nativeUI.toast(err);
				return;
			}
			toMain();
		});
	});

	mui.enterfocus('#login-form input', function() {
		mui.trigger(loginButton, 'tap');
	});

	autoLoginButton.classList[settings.autoLogin ? 'add' : 'remove']('mui-active')
	autoLoginButton.addEventListener('toggle', function(event) {
		setTimeout(function() {
			var isActive = event.detail.isActive;
			settings.autoLogin = isActive;
			app.setSettings(settings);
		}, 50);
	}, false);
	regButton.addEventListener('tap', function(event) {
		mui.openWindow({
			url: 'reg.html',
			id: 'reg',
			preload: true,
			show: {
				aniShow: 'pop-in'
			},
			styles: {
				popGesture: 'hide'
			},
			waiting: {
				autoShow: false
			}
		});
	}, false);
	forgetButton.addEventListener('tap', function(event) {
		mui.openWindow({
			url: 'forget_password.html',
			id: 'forget_password',
			preload: true,
			show: {
				aniShow: 'pop-in'
			},
			styles: {
				popGesture: 'hide'
			},
			waiting: {
				autoShow: false
			}
		});
	}, false);
	// 退出
	app.quit();
});

/**
 * 重新加载主页需要更新数据的页面
 */
function reloadMain() {
	var home = plus.webview.getWebviewById('home.html');
	var my = plus.webview.getWebviewById('my.html');

	if(home || my) {
		home.reload();
		my.reload();
	}
}